package com.hcrazy.manchester.app.services;

import java.util.List;

import com.hcrazy.manchester.app.jdbc.BookMenuDAO;
import com.hcrazy.manchester.app.pojo.BookMenu;
import com.hcrazy.manchester.app.pojo.ErrorMsg;
import com.hcrazy.manchester.app.utils.Constant;

public class BookMenuService {

	private BookMenuDAO bookMenuDAO;

	public BookMenuDAO getBookMenuDAO() {
		return bookMenuDAO;
	}

	public void setBookMenuDAO(BookMenuDAO bookMenuDAO) {
		this.bookMenuDAO = bookMenuDAO;
	}

	public ErrorMsg addOrUpdateBookMenu(BookMenu menu) throws Exception{
		ErrorMsg msg = new ErrorMsg();
		msg.setCode(Constant.SUCCESS);//success
		
		if(menu.getMenuId() > 0){
			bookMenuDAO.updateBookMenu(menu);
		}else{
			//新增分类时，如果存在父分类，则将父分类的funCode置为0
			if(menu.getMenuParent()>0){
				BookMenu parent = bookMenuDAO.getById(menu.getMenuParent());
				//获取父分类的menuCord
				String parentMenuCode = parent.getMenuCode();
				menu.setMenuCode(parentMenuCode + parent.getMenuId() + ":");
			}else{
				menu.setMenuCode(":0:");
			}
			bookMenuDAO.addBookMenu(menu);
		}
		
		return msg;
	}
	
	public List<BookMenu> getAllMenus(int type,long sellerId) throws Exception{
		List<BookMenu> list = bookMenuDAO.listAllMenus(type,sellerId);
		BookMenu root = new BookMenu();
		root.setMenuId(0);
		setChildren(root, list);
		
		return root.getChildren();
	}
	
	private void setChildren(BookMenu root,List<BookMenu> list){
		for(BookMenu menu:list){
			if(menu.getMenuParent() == root.getMenuId()){
				setChildren(menu, list);
				root.getChildren().add(menu);
			}
		}
	}
	
	public BookMenu getMenuById(int menuId) throws Exception{
		return bookMenuDAO.getById(menuId);
	}
	
	public String delBookMenu(int menuId) throws Exception{
		
		//删除子分类
		bookMenuDAO.delBookMenuByParentId(menuId);
		
		//删除本分类
		bookMenuDAO.delBookMenu(menuId);
		
		//清空所有父分类不存在的分类
		
		return null;
	}
	
}
